//
//  DataLoader.m
//  YonseiApp
//
//  Created by Hyunwoo on 5/31/10.
//  Copyright 2010 YUTAR. All rights reserved.
//

#import "DataLoader.h"


@implementation DataLoader

@synthesize tag;
@synthesize delegate;

- (id)initWithTag:(NSString *)aTag
              url:(NSString *)url
         delegate:(id <DataLoaderDelegate>)aDelegate {
    
    if ((self = [self initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:10]
                             delegate:self])) {
        tag = aTag;
        delegate = aDelegate;
        activeDownload = [[NSMutableData alloc] init];

        isLoading = YES;  
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    }
    
    return self;
}

- (id)initWithTag:(NSString *)aTag
              url:(NSString *)url
         delegate:(id<DataLoaderDelegate>)aDelegate
        superView:(UIView *)superView {
    
    if ((self = [self initWithTag:aTag url:url delegate:aDelegate])) {
        if (superView) {
            spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
            [superView addSubview:spinner];
            spinner.center = superView.center;
            spinner.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
            [spinner startAnimating];
        }
    }
    
    return self;
}

- (id)initWithTag:(NSString *)aTag
              url:(NSString *)url
         postData:(NSData *)postData
         delegate:(id <DataLoaderDelegate>)aDelegate
        superView:(UIView *)superView {
    
    
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
                                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                          timeoutInterval:10];
    [urlRequest setHTTPMethod:@"POST"];
    [urlRequest setHTTPBody:postData];
    
    if ((self = [self initWithRequest:urlRequest delegate:self])) {
        if (superView) {
            spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
            [superView addSubview:spinner];
            spinner.center = superView.center;
            spinner.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
            [spinner startAnimating];
        }
        
        tag = aTag;
        delegate = aDelegate;
        
        statusCode = -1;
        activeDownload = [[NSMutableData alloc] init];
        
        isLoading = YES;
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    }
    
    return self;
}

- (BOOL)isLoading {
    return isLoading;
}

- (void)cancel {
    isLoading = NO;
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [spinner removeFromSuperview];
    
    [super cancel];
}

#pragma mark -
#pragma mark Download support (NSURLConnectionDelegate)

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    statusCode = [(NSHTTPURLResponse *)response statusCode];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [activeDownload appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    isLoading = NO;
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [spinner stopAnimating];
    
    [delegate dataLoader:self didFinishWithData:nil tag:tag];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    isLoading = NO;
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [spinner stopAnimating];
    
    if (statusCode == 200) {
        [delegate dataLoader:self didFinishWithData:activeDownload tag:tag];
        return;
    }
    
    // on error
    if ([delegate respondsToSelector:@selector(dataLoader:didFailWithStatusCode:reason:)]) {
        NSString *reason = [[NSString alloc] initWithData:activeDownload encoding:NSUTF8StringEncoding];
        [delegate dataLoader:self didFailWithStatusCode:statusCode reason:reason];
    } else {
        [delegate dataLoader:self didFinishWithData:nil tag:tag];
    }
}

@end
